package org.smile.db.util;

import java.sql.Blob;
import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.smile.util.ClassTypeUtils;

public class ResultUtils {
	
	private static final DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public static Object getColumn(ResultSet rs,String key,Class type) throws SQLException{
		// 基础类型
		if(ClassTypeUtils.isBasicType(type)){
			if("double".equals(type.toString())){
				return rs.getDouble(key);
			}else if("int".equals(type.toString())){
				return rs.getInt(key);
			}else if("float".equals(type.toString())){
				return rs.getFloat(key);
			}else if("long".equals(type.toString())){
				return rs.getLong(key);
			}else if("short".equals(type.toString())){
				return rs.getShort(key);
			}else if("char".equals(type.toString())){
				return rs.getString(key).charAt(0);
			}
		}else{
			// 转为整型
		    if(type==Integer.class){
				return rs.getInt(key);
			}else if(type.equals(Long.class)){
				return rs.getLong(key);
			}else if(type==Short.class){
				return rs.getShort(key);
			}else if(type==String.class){
				Object value=rs.getObject(key);
	        	if(value==null){
	        		return null;
	        	}else if(value instanceof String){
	        		return  (String)value;
	        	}else if(value instanceof Clob){
	        		Clob clob=(Clob)value;
	        		int len=(int)clob.length();
	        		String str=clob.getSubString(1, len);
	        		return str;
	        	}else if(value instanceof Blob){
	        		Blob blob =(Blob)value;
	        		return new String(blob.getBytes(1, (int)blob.length()));
	        	}else if(value instanceof byte[]){
	        		return new String((byte[])value);
	        	}else if(value instanceof Byte[]){
	        		Byte[] bt=(Byte[])value;
	        		byte[] b=new byte[bt.length];
	        		for(int i=0;i<b.length;i++){
	        			b[i]=bt[i].byteValue();
	        		}
	        		return new String(b);
	        	}else if(value instanceof Date){
	        		return df.format((Date)value);
	        	}else{
	        		return new String(value+"");
	        	}
			}else if(type==Character.class){
				return rs.getString(key).charAt(0);
			}else if(type==Double.class){
				return rs.getDouble(key);
			}else if(type==Float.class){
				return rs.getFloat(key);
			}else if(type==Boolean.class){
				return rs.getBoolean(key);
			}else if(type==Date.class){
				// 转成日期类型
				return rs.getDate(key);
			}
		}
		return rs.getObject(key);
	}
}
